package repertory.android.ericchen.androidrepertory.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

import repertory.android.ericchen.androidrepertory.dao.UserBean;

/**
 * className:
 * author: Ericchen
 * description:
 * date: 2017/3/8 11:15
 * update: 2017/3/8
 * version:
 */
public class MyORMLiteDataBaseHelper extends OrmLiteSqliteOpenHelper {
    //数据库文件的名称
    private static final String TABLE_NAME = "ormsqlite-test.db";
    private MyORMLiteDataBaseHelper(Context context) {
        super(context, TABLE_NAME, null, 2);
    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase,
                         ConnectionSource connectionSource) {
        try{
            //创建表
            TableUtils.createTable(connectionSource, UserBean.class);
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase,
                          ConnectionSource connectionSource, int i, int i1) {
        try{
            TableUtils.dropTable(connectionSource, UserBean.class, true);
            onCreate(sqLiteDatabase, connectionSource);
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
    private static MyORMLiteDataBaseHelper instance;

    /*
    * 单例获取该Helper*/
    public static synchronized MyORMLiteDataBaseHelper getHelper(Context context) {
        if (instance == null){
            synchronized (MyORMLiteDataBaseHelper.class){
                if (instance == null){
                    instance = new MyORMLiteDataBaseHelper(context);
                }
            }
        }
        return instance;
    }
    /*userBean , 每张表对应一个*/
    private Dao<UserBean, Integer> userBean;
    public Dao<UserBean, Integer> getUserBean() throws SQLException {
        if (userBean == null){
            userBean = getDao(UserBean.class);
        }
        return userBean;
    }

    /*
    * 释放资源*/
    public void close(){
        super.close();
        userBean=null;
    }
}
